package com.tjcm.tjcminspectmanager;

import java.io.IOException;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.emagsoftware.ui.dialog.DialogManager;
import cn.emagsoftware.ui.staticmanager.StaticManager;
import cn.emagsoftware.util.LogManager;

import com.tjcm.tjcminspectmanager.manager.GPSManager;
import com.tjcm.tjcminspectmanager.model.KeyValue;
import com.tjcm.tjcminspectmanager.model.TaskItem;
import com.tjcm.tjcminspectmanager.model.User;

public class TaskProcessDetailActivity extends BaseActivity
{

    private TaskItem         item     = null;
    private User             user     = null;

    private LocationManager  mgr      = null;
    private LocationListener listener = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if (!LoginActivity.IS_APP_RUNNING)
        {
            StaticManager.restartAppWhenDalvikRecycled(this, LoginActivity.class);
            return;
        }
        Intent intent = getIntent();
        item = (TaskItem) intent.getSerializableExtra("TASK_ITEM");
        user = (User) intent.getSerializableExtra("USER");
        setContentView(R.layout.taskprocessdetail);

        mgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        LinearLayout itemWrap = (LinearLayout) findViewById(R.id.item_wrap);
        TextView name = (TextView) findViewById(R.id.name);
        TextView spotname = (TextView) findViewById(R.id.spotname);
        TextView starttime = (TextView) findViewById(R.id.starttime);
        TextView endtime = (TextView) findViewById(R.id.endtime);
        Button deal = (Button) findViewById(R.id.deal);
        Button back = (Button) findViewById(R.id.back);

        name.setText(item.taskName);
        spotname.setText(item.spotName);
        starttime.setText(item.startTime);
        endtime.setText(item.endTime);
        float scale = getResources().getDisplayMetrics().density;
        LinearLayout.LayoutParams keyParams = new LinearLayout.LayoutParams((int) (80 * scale + 0.5f), LinearLayout.LayoutParams.WRAP_CONTENT);
        keyParams.gravity = Gravity.CENTER_VERTICAL;
        LinearLayout.LayoutParams valueParams = new LinearLayout.LayoutParams((int) (190 * scale + 0.5f), LinearLayout.LayoutParams.WRAP_CONTENT);
        valueParams.gravity = Gravity.CENTER_VERTICAL;
        LinearLayout.LayoutParams wrapParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        wrapParams.gravity = Gravity.CENTER_HORIZONTAL;
        wrapParams.topMargin = (int) (15 * scale + 0.5f);
        String colon = getString(R.string.generic_colon);
        for (KeyValue keyValue : item.keyValues)
        {
            TextView key = new TextView(this);
            key.setText(keyValue.name.endsWith(colon) ? keyValue.name : keyValue.name + colon);
            TextView value = new TextView(this);
            value.setText(keyValue.value);
            LinearLayout wrap = new LinearLayout(this);
            wrap.addView(key, keyParams);
            wrap.addView(value, valueParams);
            itemWrap.addView(wrap, wrapParams);
        }
        deal.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                deal(true);
            }
        });
        back.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                finish();
            }
        });
        if (savedInstanceState != null)
        {
            boolean isDealing = savedInstanceState.getBoolean("IS_DEALING", false);
            if (isDealing)
            {
                deal(false);
            }
        }
    }

    private void deal(boolean isNew)
    {
        final AlertDialog progressDialog = DialogManager.showAlertDialog(this, R.string.generic_dialog_title, R.string.taskprocessdetail_btn_deal_process,
                new int[] { R.string.generic_dialog_btn_ok }, new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(final DialogInterface parentDialog, int which)
                    {
                        // TODO Auto-generated method stub
                        mgr.removeUpdates(listener);
                        GPSManager.addCurFileToQueue(TaskProcessDetailActivity.this);
                        parentDialog.dismiss();
                        listener = null;
                        Intent intent = new Intent(TaskProcessDetailActivity.this, TaskProcessSubmitActivity.class);
                        intent.putExtra("TASK_ID", item.taskId);
                        intent.putExtra("TASK_TYPE", item.taskType);
                        intent.putExtra("USER", user);
                        startActivityForResult(intent, 100);
                    }
                }, false, true);
        if (isNew)
            GPSManager.resetManager();
        listener = new LocationListener()
        {
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras)
            {
                // TODO Auto-generated method stub
            }

            @Override
            public void onProviderEnabled(String provider)
            {
                // TODO Auto-generated method stub
            }

            @Override
            public void onProviderDisabled(String provider)
            {
                // TODO Auto-generated method stub
            }

            @Override
            public void onLocationChanged(Location location)
            {
                // TODO Auto-generated method stub
                long times = location.getTime();
                double lon = location.getLongitude();
                double lat = location.getLatitude();
                try
                {
                    GPSManager.writeTaskToBinaryFile(TaskProcessDetailActivity.this, item.taskId, user.userId, lon, lat, times);
                } catch (IOException e)
                {
                    LogManager.logE(TaskProcessDetailActivity.class, "write file failed.", e);
                    mgr.removeUpdates(this);
                    progressDialog.dismiss();
                    DialogManager.showAlertDialog(TaskProcessDetailActivity.this, R.string.generic_dialog_title, R.string.taskprocessdetail_btn_deal_ioexception,
                            new int[] { R.string.generic_dialog_btn_ok }, null, true, false);
                    listener = null;
                }
            }
        };
        mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, listener);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        if (listener == null)
        {
            outState.putBoolean("IS_DEALING", false);
        } else
        {
            outState.putBoolean("IS_DEALING", true);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 100)
        {
            setResult(100);
            finish();
        }
    }

    @Override
    protected void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (listener != null)
            mgr.removeUpdates(listener);
    }

}